# -*- coding: UTF-8 -*- 
from xml.etree import ElementTree as ET
import os, time
from deal_info_api import get_home_dir, deal_info_source, judge_begin, judge_end

def deal_info_add(f_xml, li, text, tabsum):
    f_xml.write(('\t' * tabsum + '<%s>%s</%s>\n' % (li, text, li)).encode('utf-8'))

def deal_info_source(f_xml, name, full, url, invite):
    f_xml.write('\t' * 2 + '<source>\n')
    f_xml.write(('\t' * 3 + '<name>%s</name>\n' % (name)).encode('utf-8'))
    f_xml.write(('\t' * 3 + '<full>%s</full>\n' % (full)).encode('utf-8'))
    f_xml.write(('\t' * 3 + '<url>%s</url>\n' % (url)).encode('utf-8'))
    f_xml.write(('\t' * 3 + '<invite>%s</invite>\n' % (invite)).encode('utf-8'))
    f_xml.write('\t' * 2 + '</source>\n')

def deal_info_cats(f_xml, title):
    f_kw = open('%slist/keyword' % (get_home_dir()), 'r')
    while 1 + 1 == 2:
	keyword = f_kw.readline()
	if not len(keyword):
	    break

	keyword = keyword.split(':')
	if title.find(keyword[0].decode('utf-8')) > -1:
	    f_kwl = open('%slist/keywordlist' % (get_home_dir()), 'r')
	    keywordlist = eval(f_kwl.read())

	    f_xml.write(('\t' * 2 + '<cats>%s</cats>\n' % (keywordlist[keyword[0]].decode('utf-8'))).encode('utf-8'))

	    return
    
    f_xml.write('\t' * 2 + '<cats>other</cats>\n')

def deal_info_vendor(f_xml, text):
   f_xml.write('\t' * 2 + '<vendor>\n')
   f_xml.write(('\t' * 3 + '<name>%s</name>\n' % (text)).encode('utf-8'))
   if text == '':
       f_xml.write('\t' * 3 + '<url></url>\n')
   else:
       f_xml.write('\t' * 3 + '<url><![CDATA[https://encrypted.google.com/search?hl=zh-CN&q=%s]]></url>\n' % (text).encode('utf-8'))
   f_xml.write('\t' * 2 + '</vendor>\n')

def deal_info_time(f_xml):
    ut = time.gmtime(time.time() + 28800)
    t = '%Y-%m-%d'
    f_xml.write('\t' * 2 + '<start_time>%s 00:00:00+0800</start_time>\n' % (time.strftime(t, ut)))
    f_xml.write('\t' * 2 + '<end_time>%s 23:59:59+0800</end_time>\n' % (time.strftime(t, ut)))

def deal_info_discount_and_save_money(f_xml, price, value):
    f_xml.write('\t' * 2 + '<discount>%0.1f</discount>\n' % (float(price) / float(value) * 10))
    f_xml.write('\t' * 2 + '<save_money>%0.1f</save_money>\n' % (float(value) - float(price)))

def deal_info_img(f_xml, img):
    f_xml.write(('\t' * 2 + '<img><![CDATA[%s]]></img>\n' % (img)).encode('utf-8'))

def judge(f_id, d_id, deal_id):
    if d_id.find(deal_id) > -1:
	return 1
    f_id.write((deal_id + '\n').encode('utf-8'))
    return 0

